package com.cn.ant.modules.wechat.service.function.impl;

import com.cn.ant.common.utils.SpringContextHolder;
import com.cn.ant.modules.wechat.entity.WeixinAccount;
import com.cn.ant.modules.wechat.entity.message.resp.Article;
import com.cn.ant.modules.wechat.entity.message.resp.NewsMessageResp;
import com.cn.ant.modules.wechat.entity.message.resp.TextMessageResp;
import com.cn.ant.modules.wechat.service.WeixinAccountServiceImpl;
import com.cn.ant.modules.wechat.service.function.KeyServiceI;
import com.cn.ant.modules.wechat.utils.MessageUtil;

import javax.servlet.http.HttpServletRequest;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

/**
 * Created by 黄根华 on 2015/4/2.
 */
public class SiHaiService implements KeyServiceI {
    /**
     * 获取接口关键字，例如："翻译"
     *
     * @return
     */
    @Override
    public String getKey() {
        return null;
    }

    /**
     * 针对关键字的功能处理方法
     *
     * @param content        请求文本
     * @param defaultMessage 默认回复此文本消息
     * @param request        请求
     * @return
     */
    @Override
    public String excute(String content, TextMessageResp defaultMessage, HttpServletRequest request) {
        WeixinAccountServiceImpl weixinAccountService = (WeixinAccountServiceImpl) SpringContextHolder.getApplicationContext().getBean("weixinAccountService");
        WeixinAccount account = weixinAccountService.findByToUsername(defaultMessage.getFromUserName());
        String accountid = account.getId();
        ResourceBundle bundler = ResourceBundle.getBundle("application");
        List<Article> articleList = new ArrayList<Article>();
        Article article = new Article();
        article.setTitle("四海金融,送话费啦");
        article.setDescription("四海金融四周年庆,免费送话费,轻松到手!");
        article.setPicUrl(bundler.getString("domain") + "/static/images/wechat/sihai/title.png");
        String redirectUrl = null;
        try {
            redirectUrl = URLEncoder.encode(bundler.getString("domain") + "/app/idea/mobileFee","UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+account.getAccountAppId()+"" +
                "&redirect_uri="+redirectUrl+"&response_type=code&scope=snsapi_base&state="+accountid+"#wechat_redirect";
        article.setUrl(url);
        articleList.add(article);
        NewsMessageResp newsMessage = new NewsMessageResp();
        newsMessage.setToUserName(defaultMessage.getToUserName());
        newsMessage.setFromUserName(defaultMessage.getFromUserName());
        newsMessage.setCreateTime(new Date().getTime());
        newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
        newsMessage.setArticleCount(articleList.size());
        newsMessage.setArticles(articleList);
        return MessageUtil.newsMessageToXml(newsMessage);
    }
}
